package com.algorithm.window;

import org.junit.Assert;
import org.junit.Test;

import java.util.HashSet;

/**
 * 无重复字符的最长子串
 * 输入: s = "abcabcbb"
 * 输出: 3
 * 解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
 */
public class LongestSubString {

    @Test
    public void test() {
        int length = lengthOfLongestSubstring("au");
        Assert.assertEquals(length, 2);
    }

    public int lengthOfLongestSubstring(String s) {

        int longestLength = 0;

        char[] charArray = s.toCharArray();
        if (charArray.length == 1) {
            return 1;
        }


        // 从左到右滑动
        int left = 0;
        int right = 0;
        for (int i = 0; i < charArray.length - 1; i++) {
            left = i;
            right = left;
            HashSet<Character> set = new HashSet<>();
            set.add(charArray[i]);
            String leftString = s.substring(i + 1);
            char[] leftStringCharArray = leftString.toCharArray();
            for (int j = 0; j < leftStringCharArray.length; j++) {
                if (set.add(leftStringCharArray[j])) {
                    right++;
                    longestLength = Math.max(longestLength, right - left + 1);
                } else {
                    longestLength = Math.max(longestLength, right - left + 1);
                    System.out.println("记录长度：" + (right - left + 1) + ", 起始坐标：" + s.substring(left, right + 1));
                    break;
                }
            }
        }

        return longestLength;
    }

}
